package net.qhzw.vip.qiyu.service;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.entity.DtsUser;
import net.qhzw.vip.qiyu.entity.DtsUserBill;
import net.qhzw.vip.qiyu.entity.DtsUserDeduction;
import net.qhzw.vip.qiyu.entity.SysScheduledTask;
import net.qhzw.vip.qiyu.mapper.SysScheduledTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

@Service
@Transactional
@Slf4j
public class ScheduledTaskService {

    @Autowired
    private DtsUserDeductionService dtsUserDeductionService;

    @Autowired
    private DtsUserBillService dtsUserBillService;

    @Autowired
    private DtsUserService dtsUserService;

    @Autowired
    private SysScheduledTaskMapper sysScheduledTaskMapper;


    public int taskCheck() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar now = Calendar.getInstance();
        String str = now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH);
        Date today = sdf.parse(str);
        String dateNowStr1 = sdf.format(today);
        List<SysScheduledTask> list = sysScheduledTaskMapper.selectByCreateTime(dateNowStr1);
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        } else {
            return list.size();
        }

    }

    /***
     * 租车成功后每次扣费
     */
    public void execution() {
        try {
            int i = taskCheck();
            if (i > 0) {
                return;
            } else {
                SysScheduledTask sysScheduledTask = new SysScheduledTask();
                sysScheduledTask.setName("每日扣款任务");
                sysScheduledTask.setCreateTime(new Date());
                sysScheduledTaskMapper.insert(sysScheduledTask);
                log.info("执行每日扣费定时任务, 时间: {}", LocalDateTime.now());
                //查询扣费表
                List<DtsUserDeduction> userDeductions = dtsUserDeductionService
                        .list(new LambdaQueryWrapper<DtsUserDeduction>().eq(DtsUserDeduction::getStatus, 1));
                if (CollectionUtils.isEmpty(userDeductions)) {
                    return;
                }
                userDeductions.forEach(data -> data.setRent(data.getRent().abs()));
                //保存用户账单表
                List<DtsUserBill> dtsUserDeductions = new ArrayList<>(userDeductions.size());
                for (DtsUserDeduction userDeduction : userDeductions) {
                    DtsUserBill dtsUserBill = new DtsUserBill(IdWorker.getId(), userDeduction.getUserId(), (byte) 3, userDeduction.getRent().negate(), new Date());
                    dtsUserDeductions.add(dtsUserBill);
                }
                log.info("用户账单表: {}", JSON.toJSONString(dtsUserDeductions));
                dtsUserBillService.saveBatch(dtsUserDeductions);
                //更新用户余额
                Map<Long, DtsUserDeduction> userDeductionMap = new HashMap<>();
                for (DtsUserDeduction userDeduction : userDeductions) {
                    userDeductionMap.put(userDeduction.getUserId(), userDeduction);
                }
                List<Long> userIds = userDeductions.stream().map(DtsUserDeduction::getUserId).collect(Collectors.toList());
                List<DtsUser> dtsUsers = dtsUserService.list(new LambdaQueryWrapper<DtsUser>().in(DtsUser::getId, userIds));
                List<DtsUser> dtsUserList = new ArrayList<>();
                for (DtsUser dtsUser : dtsUsers) {
                    for (Map.Entry<Long, DtsUserDeduction> entry : userDeductionMap.entrySet()) {
                        if (entry.getKey().equals(dtsUser.getId())) {
                            BigDecimal decimal = dtsUser.getBalance().subtract(entry.getValue().getRent());
                            DtsUser dtsUserDB = new DtsUser();
                            dtsUserDB.setBalance(decimal);
                            dtsUserDB.setId(dtsUser.getId());
                            dtsUserList.add(dtsUserDB);
                        }
                    }
                }
                log.info("更新用户余额: {}", JSON.toJSONString(dtsUserList));
                dtsUserService.updateBatchById(dtsUserList);
            }
        } catch (Exception e) {
            log.info("每日扣款异常, 时间: {}", LocalDateTime.now());
        }


    }
}
